package com.demo.example.hot100;

import java.util.HashMap;
import java.util.Map;

public class TheLongestSubStringWithoutRepeat {
    public static void main(String[] args) {
        String s=new String("pwwkew");
       lengthOfLongestSubstring(s);
    }
    //暴力解法 O(n^2)
    public static int lengthOfLongestSubstring(String s){
        if(s==null || s.length()==0){
            return 0;
        }
        int max=1;
        for(int i=0;i<s.length()-1;i++){
            Map<Character,Integer> map=new HashMap<>();
            map.put(s.charAt(i),1);
            int tmp=1;
            for(int j=i+1;j<s.length();j++){
                if(map.containsKey(s.charAt(j))){
                    if(tmp>max){
                        max=tmp;
                    }
                    break;
                }else{
                    map.put(s.charAt(j),1);
                    tmp++;
                    if(tmp>max){
                        max=tmp;
                    }
                }
            }
        }
        return  max;
    }
    //滑动窗口解法
    public static int lengthOfLongestSubstring2(String s){
        int length = s.length();
        int max = 0;

        Map<Character, Integer> map = new HashMap<>();
        for(int start = 0, end = 0; end < length; end++){
            char element = s.charAt(end);
            if(map.containsKey(element)){
                start = Math.max(map.get(element) + 1, start); //map.get()的地方进行+1操作
            }
            max = Math.max(max, end - start + 1);
            map.put(element, end);
        }
        return max;
    }
}
